package com.jkm.service.impl;

import com.jkm.redis.KeyPrefix;
import com.jkm.service.RedisService;
import com.jkm.util.JsonUtil;
import com.jkm.util.NullUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: liyabin
 * @Date: 2018/6/14 14:18
 * @Description:
 */
@Slf4j
@Service
public class RedisServiceImpl implements RedisService {
    /***
     * redis 服务
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public <T> T get(KeyPrefix prefix, String key, Class<T> bean) {
        Object jsonStr = redisTemplate.opsForValue().get(prefix.getPrefix() + key);
        if (NullUtils.isEmpty(jsonStr)) return null;
        T baans = (T)jsonStr;
//        return JsonUtil.StringToJSONObject(jsonStr.toString()).toJavaObject(bean);
        return baans;
    }


    @Override
    public <T> boolean set(KeyPrefix prefix, String key, T value) {
        String add_key = prefix.getPrefix() + key;
        try {
            redisTemplate.opsForValue().set(add_key, value, prefix.expireSeconds(), TimeUnit.SECONDS);
        } catch (Exception e) {
            log.info(e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public boolean exists(KeyPrefix prefix, String key) {
        Object result = redisTemplate.opsForValue().get(prefix.getPrefix() + key);
        return !NullUtils.isEmpty(result);
    }

    @Override
    public boolean delete(KeyPrefix prefix, String key) {
        redisTemplate.delete(prefix.getPrefix() + key);
        return true;
    }

    @Override
    public Long incr(KeyPrefix prefix, String key) {
        return redisTemplate.opsForValue().increment(prefix.getPrefix() + key, 1L);
    }

    @Override
    public Long decr(KeyPrefix prefix, String key) {
        return redisTemplate.opsForValue().increment(prefix.getPrefix() + key, -1L);
    }
}
